package com.wennimei.service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.wennimei.util.HttpUtil;
import com.wennimei.util.TimeUtil;

@Service
public class HoroscopeService {

    private final String url = "http://vip.astro.sina.com.cn/astro/view/%s/day/%s";

    private final String regx = ".*<div class=\"lotconts\">(.*)?</div>.*";

    private final Pattern pattern = Pattern.compile(regx);

    private static final Map<String, String> map = new HashMap<String, String>();

    @PostConstruct
    void init() {
        map.put("白羊", "aries");
        map.put("金牛", "taurus");
        map.put("双子", "gemini");
        map.put("巨蟹", "cancer");
        map.put("狮子", "leo");
        map.put("处女", "virgo");
        map.put("天秤", "libra");
        map.put("天蝎", "scorpio");
        map.put("射手", "sagittarius");
        map.put("魔羯", "capricorn");
        map.put("水瓶", "aquarius");
        map.put("双鱼", "pisces");
    }

    static {
        map.put("白羊", "aries");
        map.put("金牛", "taurus");
        map.put("双子", "gemini");
        map.put("巨蟹", "cancer");
        map.put("狮子", "leo");
        map.put("处女", "virgo");
        map.put("天秤", "libra");
        map.put("天蝎", "scorpio");
        map.put("射手", "sagittarius");
        map.put("魔羯", "capricorn");
        map.put("水瓶", "aquarius");
        map.put("双鱼", "pisces");
    }

    public String get(String content) {
        String day = new SimpleDateFormat("yyyyMMdd").format(new Date());
        if (content.contains("明天") || content.matches("明日"))
            day = TimeUtil.formatDate(
                    TimeUtil.getDayBeforeAfter(new Date(), 1), "yyyyMMdd");

        String type = "aries";
        for (String s: map.keySet()) {
            if (content.contains(s)) {
                type = map.get(s);
                break;
            }
        }

        byte[] b = HttpUtil.getByte(String.format(url, type, day));
        String result = "暂未查询到此星座运势信息，请输入“白羊运势”“白羊明日运势”等重新查询";
        String json;
        try {
            json = new String(b, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return result;
        }
        Matcher matcher = pattern.matcher(json);
        while (matcher.find()) {
            result = matcher.group(1);
            break;
        }
        return result;
    }
}
